package cn.net.isir.controller.manager;

import cn.net.isir.common.ResultObject;
import cn.net.isir.common.TokenManager;
import cn.net.isir.entity.*;
import cn.net.isir.service.*;
import cn.net.isir.service2.ShopService;
import cn.net.isir.utils.DateUtils;
import cn.net.isir.utils.JSONUtils;
import cn.net.isir.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author liuxubo
 * @filename TurnSalesmanController.java
 * @package cn.net.isir.controller.manager
 * @email lxb@isir.net.cn
 * @date 2019/03/13
 * @comment
 * @since 1.8
 */
@RestController
@RequestMapping("/turnstatistics")
public class TurnSalesmanController {
    @Resource
    private CRMUserManagerService crmUserManagerService;
    @Resource
    private UserService userService;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private TurnShopService turnShopService;
    @Resource
    private TurnService turnService;
    @Resource
    private ShopService shopService;
    @Resource
    private BankCardService bankCardService;


    /**
     * 转结汇总统计列表信息
     *
     * @param userInfo 用户信息
     * @return 列表
     */
    @RequestMapping(value = "/listByUser", method = RequestMethod.GET)
    public ResultObject list(UserInfo userInfo) {
        String name = userInfo.getName();
        String userId = userInfo.getUserId();
        Date startTime = userInfo.getStartTime();
        Date endTime = userInfo.getEndTime();
        String tokenId = TokenManager.getTokenId();
        // 根据用户id查询销售人员ID(自己管理下的所有人员,不包括自己同组织机构的人员)
        Set<String> userIds = crmUserManagerService.getSalesmanIdByUserId(tokenId);
        userIds.add(tokenId);
        //查询条件-人员

        Set<String> resultUserId = userIds;
        if (StringUtils.isNotBlank(name) || StringUtils.isNotBlank(userId)) {
            resultUserId = new HashSet<>();
            User user = new User();
            if (StringUtils.isNotBlank(name)) {
                user.setName(name);
            }
            if (StringUtils.isNotBlank(userId)) {
                user.setId(userId);
            }

            // 获取其他字段信息
            List<User> searchUserList = userService.selectList(user);
            //获取搜索结果和人员列表的交集
            for (String id : userIds) {
                boolean isExist = false;
                for (User user1 : searchUserList) {
                    if (id.equals(user1.getId())) {
                        isExist = true;
                    }
                }
                if (isExist) {
                    resultUserId.add(id);
                }
            }
        }
        //根据这些人查询turn表
        StringBuilder sb = new StringBuilder();
        resultUserId.forEach(i -> sb.append(i).append(","));
        String ids = null;
        if (sb.length() > 0) {
            ids = sb.substring(0, sb.length() - 1);
        }
        Turn t = new Turn();
        t.setQueryUserId(ids);
        if (startTime != null) {
            t.setStartTime(startTime);
        }
        if (endTime != null) {
            t.setEndTime(endTime);
        }
        //查询turn列表
        PageInfo turnPage = turnService.selectPageList(t, userInfo.getPageNo(), userInfo.getPageSize());
        //其他扩展字段（单独查询）
        JSONArray jsonArray = new JSONArray();
        for (Object turnObject : turnPage.getList()) {
            Turn turn = (Turn) turnObject;
            BigDecimal turnFee = turn.getTurnFee().setScale(3,BigDecimal.ROUND_HALF_UP);
            turn.setTurnFee(turnFee);
            JSONObject jsonObject = JSONUtils.toJSONObject(turn);
            //查询userName
            UserInfo userInfo1 = new UserInfo();
            userInfo1.setUserId(turn.getUserId());
            UserInfo u = userInfoService.selectOne(userInfo1);

            TurnShop turnShop = new TurnShop();
            turnShop.setTurnId(turn.getId());
            List<TurnShop> turnShops = turnShopService.selectList(turnShop);
            int count = 0;
            for (TurnShop turnshoplist : turnShops) {
                if (new BigDecimal("0.000000").compareTo(turnshoplist.getTurnAmount()) < 0) {
                    count++;
                }
            }
            jsonObject.put("turnCount", count);
            jsonObject.put("username", u.getName());
            jsonArray.add(jsonObject);
        }
        turnPage.setList(jsonArray);
        return new ResultObject(200, "success", turnPage);
    }

    /**
     * 转结汇总统计列表信息
     *
     * @param turnId,shopName 多个列表
     * @return 列表
     */
    @RequestMapping(value = "/shoplist", method = RequestMethod.GET)
    public ResultObject shoplist(String turnId, String shopName, Integer pageNo, Integer pageSize) {
        StringBuilder sb = new StringBuilder();
        String shopIds = null;
        //根据shopName在shop表中查询shopIds
        if (StringUtils.isNotBlank(shopName)) {
            Shop shop = new Shop();
            try {
                shop.setName(URLDecoder.decode(shopName, StandardCharsets.UTF_8.name()));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            List<Shop> shopList = shopService.selectList(shop);
            if (shopList.size() == 0) {
                return new ResultObject(200, "success", new PageInfo<>());
            }
            for (Shop shoplist : shopList) {
                sb.append(shoplist.getId()).append(",");
            }
            if (sb.length() > 0) {
                shopIds = sb.substring(0, sb.length() - 1);
            }
        }
        //根据turnId在TurnShop中查询List
        TurnShop ts = new TurnShop();
        ts.setTurnId(turnId);
        ts.setQueryUserId(shopIds);
        PageInfo turnShopPage = turnShopService.selectPageList(ts, pageNo, pageSize);
        //扩展字段
        Turn turn = turnService.selectByPrimaryKey(turnId);
        turn.getMonthPercent();//转前当月百分比
        turn.getTurnPercent();//转出累计百分比

        //其他扩展字段（单独查询）
        JSONArray jsonArray = new JSONArray();
        for (Object turnObject : turnShopPage.getList()) {
            TurnShop turnShop = (TurnShop) turnObject;
            BigDecimal monthFee = turnShop.getMonthFee().setScale(3, BigDecimal.ROUND_HALF_UP);
            turnShop.setMonthFee(monthFee);
            BigDecimal turnFee = turnShop.getTurnFee().setScale(3, BigDecimal.ROUND_HALF_UP);
            turnShop.setTurnFee(turnFee);
            JSONObject jsonObject = JSONUtils.toJSONObject(turnShop);
            jsonObject.put("shopName", shopService.selectByPrimaryKey(turnShop.getShopId()).getName());
            jsonObject.put("monthPercent", turn.getMonthPercent());
            jsonObject.put("turnPercent", turn.getTurnPercent());
            jsonArray.add(jsonObject);
        }
        turnShopPage.setList(jsonArray);
        return new ResultObject(200, "success", turnShopPage);
    }

    /**
     * 转结汇总统计列表信息
     *
     * @param userInfo 多个列表
     * @return 列表
     */
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public ResultObject export(UserInfo userInfo, HttpServletRequest request, HttpServletResponse response) {
        // 表格准备
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet;
        HSSFRow row;
        HSSFCell cell;
        HSSFCellStyle style;
        HSSFFont font;
        int rowIndex = 0;
        int cellIndex = 0;

        // sheet2
        HSSFSheet sheet2;
        HSSFRow row2;
        HSSFCell cell2;
        int rowIndex2 = 0;
        int cellIndex2 = 0;

        sheet = workbook.createSheet("人员列表");

        // 设置标题格式
        style = workbook.createCellStyle();
        font = workbook.createFont();
        font.setBold(true);
        style.setFont(font);
        // 写入标题
        row = sheet.createRow(rowIndex);
        cell = row.createCell(cellIndex);
        cell.setCellStyle(style);
        cell.setCellValue("人员ID");
        cell = row.createCell(++cellIndex);
        cell.setCellStyle(style);
        cell.setCellValue("人员姓名");
        cell = row.createCell(++cellIndex);
        cell.setCellStyle(style);
        cell.setCellValue("转出店铺数量");
        cell = row.createCell(++cellIndex);
        cell.setCellStyle(style);
        cell.setCellValue("转出佣金");
        cell = row.createCell(++cellIndex);
        cell.setCellStyle(style);
        cell.setCellValue("转出卡号");
        cell = row.createCell(++cellIndex);
        cell.setCellStyle(style);
        cell.setCellValue("开户行支行");

        sheet2 = workbook.createSheet("店铺列表");
        row2 = sheet2.createRow(rowIndex2);
        cell2 = row2.createCell(cellIndex2);
        cell2.setCellStyle(style);
        cell2.setCellValue("人员ID");
        cell2 = row2.createCell(++cellIndex2);
        cell2.setCellStyle(style);
        cell2.setCellValue("人员姓名");
        cell2 = row2.createCell(++cellIndex2);
        cell2.setCellStyle(style);
        cell2.setCellValue("转出店铺名称");
        cell2 = row2.createCell(++cellIndex2);
        cell2.setCellStyle(style);
        cell2.setCellValue("转出佣金");

        PageInfo turnPage = (PageInfo) list(userInfo).getObject();
        JSONArray turnList = (JSONArray) turnPage.getList();
        //获取小程序中绑定银行卡时填写的人员姓名

        for (Object obj : turnList) {
            JSONObject turnJO = JSONObject.parseObject(JSON.toJSONString(obj));
            BankCard bankCard = new BankCard();
            bankCard.setUserId(turnJO.getString("userId"));
            bankCard = bankCardService.selectOne(bankCard);
            // 设置正文字体
            font.setBold(false);
            style.setFont(font);
            // 写入内容
            row = sheet.createRow(++rowIndex);
            cellIndex = 0;
            // ID
            cell = row.createCell(cellIndex++);
            cell.setCellStyle(style);
            cell.setCellValue(turnJO.getString("userId"));
            // 姓名
            cell = row.createCell(cellIndex++);
            cell.setCellStyle(style);
            try {
                cell.setCellValue(bankCard.getName());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            // 店铺数量
            cell = row.createCell(cellIndex++);
            cell.setCellStyle(style);
            cell.setCellValue(turnJO.getString("turnCount"));
            // 转出佣金
            cell = row.createCell(cellIndex++);
            cell.setCellStyle(style);
            cell.setCellValue(turnJO.getString("turnFee"));
            // 转出卡号
            cell = row.createCell(cellIndex++);
            cell.setCellStyle(style);

            cell.setCellValue(bankCard.getCardNo());
            //开户行支行
            cell = row.createCell(cellIndex++);
            cell.setCellStyle(style);
            cell.setCellValue(bankCard.getBelongTo());
            // 更新转出状态
            Turn turn = turnService.selectByPrimaryKey(turnJO.getString("id"));
            turn.setIsExported(turn.getIsExported() + 1);
            turnService.update(turn);

//            int startMergeRowIndex = rowIndex2;

            PageInfo turnShopPage = (PageInfo) shoplist(turnJO.getString("id"), null, 1, 0).getObject();
            JSONArray turnShopList = (JSONArray) turnShopPage.getList();
            // 店铺列表
            for (Object obj2 : turnShopList) {
                JSONObject turnShopJO = JSONObject.parseObject(JSON.toJSONString(obj2));

                row2 = sheet2.createRow(++rowIndex2);
                cellIndex2 = 0;
                int startMergeRowIndex = rowIndex2;
                // ID
                cell2 = row2.createCell(cellIndex2++);
                cell2.setCellStyle(style);
                cell2.setCellValue(String.valueOf(turnShopJO.get("id")));
                // 姓名
                cell2 = row2.createCell(cellIndex2++);
                cell2.setCellStyle(style);
                try {
                    cell2.setCellValue(turnJO.getString("username"));
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                // 转出店铺名称
                cell2 = row2.createCell(cellIndex2++);
                cell2.setCellStyle(style);
                Shop shop = shopService.selectByPrimaryKey(turnShopJO.getString("shopId"));
                cell2.setCellValue(shop.getName());
                // 转出佣金
                cell2 = row2.createCell(cellIndex2++);
                cell2.setCellStyle(style);
                cell2.setCellValue(((BigDecimal) turnShopJO.get("turnFee")).doubleValue());

                //合并同一个销售人员的多个店铺（合并人员信息）
                if (turnShopList.size()>1) {
                    sheet2.addMergedRegion(new CellRangeAddress(startMergeRowIndex, startMergeRowIndex + turnShopList.size() - 1,
                            0, 0));
                    sheet2.addMergedRegion(new CellRangeAddress(startMergeRowIndex, startMergeRowIndex + turnShopList.size() - 1,
                            1, 1));
                }
            }
        }

        // 宽度自适应
        for (int i = 0; i < cellIndex; i++) {
            sheet.autoSizeColumn(i);
            sheet.autoSizeColumn(i, true);
        }
        for (int i = 0; i < cellIndex2; i++) {
            sheet.autoSizeColumn(i);
            sheet2.autoSizeColumn(i, true);
        }

        String filename = "转出人员-" + DateUtils.format(new Date(), "yyyyMMddHHmmss") + ".xls";
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" +
                new String(filename.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1) + ".xls");
        try {
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


}
